package com.hjk.common.utils.io;

import cn.hutool.core.io.IoUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.hjk.common.model.UserInfo;
import com.hjk.common.utils.check.Check;
import com.hjk.common.utils.concurrency.RuntimeUtils;
import com.hjk.common.utils.string.LogUtils;
import com.hjk.common.utils.string.JsonUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.junit.Test;

import java.io.*;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;

/**
 * @author huangjunkai
 * @version 1.0
 * @date 2020/5/31 4:03
 */
@Slf4j
public class IoUtils {
    /**
     * 读取资源路径下json文件成 jsonNode
     * @param filePathName 文件名
     * @return JsonNode
     */
    public static JsonNode readResourceFileToJson(String filePathName) {
       try ( InputStream inputStream = IoUtils.class.getClassLoader().getResourceAsStream(filePathName)){
           if (Check.isNotEmpty(inputStream)) {
               return JsonUtils.MAPPER.readTree(inputStream);
           }
       } catch (Exception e) {
             e.printStackTrace();
        }
        return null;
    }

    /**
     * 生成json文件
     * @param filePathName 文件名
     * @return JsonNode
     */
    @SneakyThrows
    public static void wireToJsonFile(Object json,String filePathName) {
        String format = JsonUtils.jsonFormat(json);
        if (Check.isNotEmpty(format)) {
            IOUtils.write(format.getBytes(),new FileOutputStream(new File(filePathName)));
        }
    }

    @Test
    public void test33(){
        wireToJsonFile(new UserInfo(),"G:\\UserInfo.json");
    }

    /**
     * 文件拷贝 BIO
     *
     * @param src
     * @param dest
     */
    public static void copyFileBio(String src, String dest) {
        try (
                InputStream is = new BufferedInputStream(new FileInputStream(src));
                OutputStream os = new BufferedOutputStream(new FileOutputStream(dest));
        ) {
            byte[] bytes = new byte[1024];
            int len;
            while ((len = is.read(bytes)) != -1) {
                os.write(bytes, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 读取文件成字符串
     *
     * @param filePath
     */
    public static String fileToString(String filePath) {
        Check.checkStrIsNotBlank(filePath, "地址值不能为空");
        File file = new File(filePath);
        long fileLength = file.length();
        if (fileLength > RuntimeUtils.getFreeMemory() / 2) {
            throw new RuntimeException(LogUtils.format("[ {} ] 文件太大了!!!",file.getPath()));
        }
        try (
                FileInputStream input = new FileInputStream(filePath)
        ) {
            //获取管道
            FileChannel channel = input.getChannel();
            //创建缓冲区
            ByteBuffer byteBuffer = ByteBuffer.allocate((int) file.length());
            //数据读到缓冲区
            channel.read(byteBuffer);
            return new String(byteBuffer.array(), StandardCharsets.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();

        }
        return null;
    }



    public static void main(String[] args)throws Exception {
        //String f = "G:\\my_tool\\common\\src\\main\\java\\com\\hjk\\common\\utils\\io\\FileUtils.java";
        String file = fileToString("E:\\soft\\DevelopmentKit\\java\\ideaIU-2020.2.1.exe");
        //String file = fileToString(f);

        //String s = IOUtils.toString(new FileInputStream("E:\\soft\\DevelopmentKit\\java\\ideaIU-2020.2.1.exe"), StandardCharsets.UTF_8);
        System.out.println(file);
      // System.out.println(s);

    }

    /**
     * 下载图片
     *
     * @param url  图片url
     * @param path 文件保存路径
     */
    public static void download(String url, String path) {
        //文件下载保存路径

        try (

                BufferedInputStream bis =
                        new BufferedInputStream(new DataInputStream(new URL(url).openStream()));
                BufferedOutputStream bos =
                        new BufferedOutputStream(new FileOutputStream(new File(path)));
        ) {


            int len;
            byte[] bytes = new byte[1024];
            while ((len = bis.read(bytes)) != -1) {
                bos.write(bytes, 0, len);
            }
            log.info("文件下载成功: {}",path);
        } catch (IOException e) {
            log.error("文件下载错误:{}",url,e);
        }

    }

    /**
     * 下载图片
     *
     * @param url  图片url
     * @param path 文件保存路径
     */
    public static void downloadToPath(String url, String path) {
        //文件下载保存路径
        try{
                InputStream inputStream = new URL(url).openStream();
                int copy = IOUtils.copy(new DataInputStream(inputStream),
                       new FileOutputStream(new File(path)));
                log.info("文件下载成功: {} ,保存路径 : {} ",url,path);

        } catch (IOException e) {
            log.error("文件下载错误:{}",url,e);
        }

    }


}
